package com.example.book.api;

import com.example.book.base.ApiBaseController;
import com.example.book.base.Result;
import com.example.book.common.annotation.LoginIgnore;
import com.example.book.common.utils.Constants;
import com.example.book.common.utils.RedisService;
import com.example.book.domain.wx.UserInfo;
import com.example.book.in.entity.BookCatalog;
import com.example.book.in.entity.BookContent;
import com.example.book.in.entity.UserReadRecord;
import com.example.book.in.service.BookCatalogService;
import com.example.book.in.service.BookContentService;
import com.example.book.in.service.UserReadRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/book")
public class ApiBookCatalogController extends ApiBaseController {

    private BookCatalogService catalogService;
    private BookContentService contentService;
    private RedisService redisService;
    private UserReadRecordService readRecordService;

    private ApiBookCatalogController(BookCatalogService catalogService, BookContentService contentService, RedisService redisService, UserReadRecordService readRecordService) {
        this.catalogService = catalogService;
        this.contentService = contentService;
        this.redisService = redisService;
        this.readRecordService = readRecordService;
    }

    /**
     * 用户点击阅读按钮检测用户是登录
     * 检测用户本书是否有阅读记录
     * 返回用户要读的书籍章节id 和 章节索引
     * @param readRecord
     * @return
     */
    @GetMapping("/catalog/read")
    @LoginIgnore
    public Result readBookByCatalog(UserReadRecord readRecord) {

        String token = getToken();
        UserInfo userInfo = null;
        if (StringUtils.isNotBlank(token)) {
            userInfo = (UserInfo) redisService.get(Constants.WX_API_TOKEN + token);
        }

        BookCatalog catalog = new BookCatalog();
        catalog.setBookInfoId(readRecord.getBookInfoId());

        BookCatalog bc = null;
        if (userInfo == null) {
            bc = catalogService.selectOrderByIndexAsc(catalog);
        } else {
            readRecord.setUserId(userInfo.getUid());
            UserReadRecord record = readRecordService.findTheLastRecord(readRecord);
            // 读取本书第一条目录id
            if (record == null) {
                bc = catalogService.selectOrderByIndexAsc(catalog);
            } else {
                // d读取用户记录
                BookCatalog bookCatalog = new BookCatalog();
                bookCatalog.setId(record.getBookCatalogId());
                bc = catalogService.get(bookCatalog);
            }
        }

        // 还没有目录
        if (bc == null){
            return Result.error();
        }

        Map<String, Object> map = new HashMap<>();
        map.put("id", bc.getId());
        map.put("catalogIndex", bc.getCatalogIndex());

        return Result.success("success", map);
    }

    /**
     * 获取书籍目录对应的内容
     *
     * @param content
     * @return
     */
    @GetMapping("/content")
    @LoginIgnore
    public Result getContent(BookContent content) {

        BookContent bookContent = contentService.get(content);

        if (bookContent == null) {
            return Result.error();
        }

        BookCatalog bc = new BookCatalog();
        bc.setId(bookContent.getBookCatalogId());
        BookCatalog catalog = catalogService.get(bc);

        // 上一章
        catalog.setType("0");
        BookCatalog previousChapter = catalogService.previousChapterOrNextChapter(catalog);

        // 下一章
        catalog.setType("1");
        BookCatalog nextChapter = catalogService.previousChapterOrNextChapter(catalog);

        Map<String, Object> map = new HashMap<>();

        if (previousChapter != null) {
            map.put("previous", true);
            map.put("previousChapter", previousChapter.getId());
        } else {
            map.put("previous", false);
            map.put("previousChapter", "0");
        }

        if (nextChapter != null) {
            map.put("next", true);
            map.put("nextChapter", nextChapter.getId());
        } else {
            map.put("next", false);
            map.put("nextChapter", "0");
        }

        map.put("catalogName", catalog.getCatalogName());
        map.put("content", bookContent.getContent());

        try {
            // 没出息加载内容记录阅读的章节
            String token = getToken();
            if (StringUtils.isNotBlank(token)){
                UserInfo userInfo = (UserInfo) redisService.get(Constants.WX_API_TOKEN + token);
                if (userInfo!=null){
                    UserReadRecord readRecord = new UserReadRecord();
                    readRecord.setUserId(userInfo.getUid());
                    readRecord.setBookInfoId(catalog.getBookInfoId());
                    readRecord.setBookCatalogId(catalog.getId());
                    readRecordService.save(readRecord);
                }
            }
        }catch (Exception e){
            // 只是保证能够一定返回内容
        }

        return Result.success("success", map);
    }

    /**
     * 加载书籍目录
     *
     * @param id
     * @return
     */
    @GetMapping("/catalog")
    @LoginIgnore
    public Result findList(String id) {

        BookCatalog bookCatalog = new BookCatalog();
        bookCatalog.setBookInfoId(id);
        List<BookCatalog> list = catalogService.findList(bookCatalog);
        if (list.size() < 1) {
            return Result.error();
        }

        List<Map<String, Object>> maps = new ArrayList<>();
        Map<String, Object> map = null;
        for (BookCatalog bc : list) {
            map = new HashMap<>();
            map.put("id", bc.getId());
            map.put("name", bc.getCatalogName());
            map.put("catalogIndex", bc.getCatalogIndex());
            maps.add(map);
        }

        if (maps.size() < 1) {
            return Result.error("no data");
        }

        return Result.success(maps);
    }

}
